package com.lh.pospi.x_store.utils;

import android.app.Dialog;
import android.content.Context;

import com.google.gson.Gson;
import com.itheima.retrofitutils.ItheimaHttp;
import com.itheima.retrofitutils.Request;
import com.itheima.retrofitutils.listener.HttpResponseListener;
import com.lany.sp.SPHelper;
import com.lh.pospi.x_store.api.Api;
import com.lh.pospi.x_store.app.MyApp;
import com.lh.pospi.x_store.modle.BaseT;
import com.lh.pospi.x_store.modle.BrandBean;
import com.lh.pospi.x_store.modle.CatBean;
import com.lh.pospi.x_store.modle.CusBean;
import com.lh.pospi.x_store.modle.GoodsBean;
import com.lh.pospi.x_store.modle.MarktBean;
import com.lh.pospi.x_store.modle.RequestBrand;
import com.lh.pospi.x_store.modle.RequestCat;
import com.lh.pospi.x_store.modle.RequestCus;
import com.lh.pospi.x_store.modle.RequestGoods;
import com.lh.pospi.x_store.modle.RequestMark;
import com.lh.pospi.x_store.modle.RequestStock;
import com.lh.pospi.x_store.modle.RequestSup;
import com.lh.pospi.x_store.modle.RequestUser;
import com.lh.pospi.x_store.modle.StockBean;
import com.lh.pospi.x_store.modle.SupBean;
import com.lh.pospi.x_store.modle.UserBean;
import com.lh.pospi.x_store.net.NetHelper;
import com.lh.pospi.x_store.view.ProgressDialog;
import com.vondear.rxtool.RxLogTool;
import com.vondear.rxtool.view.RxToast;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DownHelper {
    private int page = 1; //商品
    private int page_mark = 1;//门店
    private int page_sup = 1;//供应商
    private int page_user = 1;//操作员
    private int page_cus = 1;//客户
    private int page_stock = 1;//库存
    private int page_brand = 1;//品牌
    private int page_cat = 1;//品牌
    private LoadingUtil util;
    private String dbname = "yzy";

    private Context mContext;
    private ProgressDialog dialog;

    public DownHelper(Context context) {
        mContext = context;

        dbname = SPHelper.getInstance().getString(Constant.DB_NAME);
    }

    public DownHelper() {
        dbname = SPHelper.getInstance().getString(Constant.DB_NAME);
    }


    public interface CountLister {
        void getCount(int count);
    }

    public void getGoodsSize(final CountLister lister) {
        getMark();
        getsup();
        getbrand();
        getCat();
        getcus();
        downUser();
        Map<String, Object> request = new HashMap<>();
        request.put("table", "GOODSBASE");
        request.put("page", String.valueOf(page));
        request.put("pagesize", String.valueOf(1));
        request.put("dbname", dbname);
        NetHelper.request().downGoods(request).subscribeOn(Schedulers.io())//在io线程请求
                .observeOn(AndroidSchedulers.mainThread())//在主线程处理
                .subscribe(new Observer<RequestGoods>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(RequestGoods value) {
                        int count = 0;
                        if (value == null) {
                            RxToast.normal("json解析错误");
                            count = 0;
                        } else {
                            count = Integer.parseInt(value.getCount());
                            downGoods(count);
                        }
                        lister.getCount(count);
                    }

                    @Override
                    public void onError(Throwable e) {
                        lister.getCount(0);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void downGoods(int max) {
        Api api = NetHelper.request();
        int pageTotal = max / 400+1; //合计请求次数
        for (int index = 1; index <= pageTotal; index++) {
            final Map<String, Object> request = new HashMap<>();
            request.put("table", "GOODSBASE");
            request.put("page", index);
            request.put("pagesize", String.valueOf(400));
            request.put("dbname", dbname);
            api.downGoods(request).subscribeOn(Schedulers.io())//在io线程请求
                    .observeOn(Schedulers.io())//
                    .subscribe(new Observer<RequestGoods>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(RequestGoods requestGoods) {
                            if (requestGoods == null) {
                                return;
                            }
                            RxLogTool.e("数据："+requestGoods.toString());
                            if (requestGoods.getFlag() == 1) {
                                List<GoodsBean> itemsBeans = requestGoods.getResult();
                                if (itemsBeans.size() > 0) {
                                    MyApp.getInstance().getDaoSession().getGoodsBeanDao().deleteAll();
                                    MyApp.getInstance().getDaoSession().getGoodsBeanDao().insertInTx(itemsBeans);
                                }
//                    MyApp.getInstance().getDaoSession().getGoodsBeanDao().insertInTx(itemsBeans);


                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });

        }
    }
    private void getMark(){
        Map<String, Object> request = new HashMap<>();
        request.put("table", "MARKET");
        request.put("page", 1);
        request.put("pagesize", 1);
        request.put("dbname", dbname);
        NetHelper.request().downMark(request).subscribeOn(Schedulers.io())//在io线程请求
                .observeOn(Schedulers.io())//
                .subscribe(new Observer<RequestMark>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(RequestMark requestMark) {
                        if (requestMark == null) {
                            return;
                        }
                        downMark(Integer.parseInt(requestMark.getCount()));

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void downMark(int max) {
        Api api = NetHelper.request();
        int pageTotal = max / 400+1; //合计请求次数
        for (int index = 1; index <= pageTotal; index++) {
            Map<String, Object> request = new HashMap<>();
            request.put("table", "MARKET");
            request.put("page", index);
            request.put("pagesize", String.valueOf(400));
            request.put("dbname", dbname);
            api.downMark(request).subscribeOn(Schedulers.io())//在io线程请求
                    .observeOn(Schedulers.io())//
                    .subscribe(new Observer<RequestMark>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(RequestMark requestMark) {
                            if (requestMark == null) {
                                return;
                            }
                            if (requestMark.getFlag() == 1) {

                                List<MarktBean> itemsBeans = requestMark.getResult();
                                if (itemsBeans.size() > 0) {
                                    MyApp.getInstance().getDaoSession().getMarktBeanDao().deleteAll();
                                    MyApp.getInstance().getDaoSession().getMarktBeanDao().insertInTx(itemsBeans);
                                }
//                    MyApp.getInstance().getDaoSession().getGoodsBeanDao().insertInTx(itemsBeans);

                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }
    private void getsup() {
        Map<String, Object> request = new HashMap<>();
        request.put("table", "SUPPLIER");
        request.put("page", 1);
        request.put("pagesize", 1);
        request.put("dbname", dbname);
        NetHelper.request().downSup(request).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new Observer<RequestSup>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(RequestSup requestSup) {
                        if (requestSup == null) {
                            return;
                        }
                       downSup(Integer.parseInt(requestSup.getCount()));
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void downSup(int max) {
        Api api = NetHelper.request();
        int pageTotal = max / 400+1; //合计请求次数
        for (int index = 1; index <= pageTotal; index++) {
            Map<String, Object> request = new HashMap<>();
            request.put("table", "SUPPLIER");
            request.put("page", index);
            request.put("pagesize", String.valueOf(400));
            request.put("dbname", dbname);
            api.downSup(request).subscribeOn(Schedulers.io())
                    .observeOn(Schedulers.io())
                    .subscribe(new Observer<RequestSup>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(RequestSup requestSup) {
                            if (requestSup == null) {
                                return;
                            }
                            if (requestSup.getFlag() == 1) {

                                List<SupBean> itemsBeans = requestSup.getResult();
                                if (itemsBeans.size() > 0) {
                                    MyApp.getInstance().getDaoSession().getSupBeanDao().deleteAll();
                                    MyApp.getInstance().getDaoSession().getSupBeanDao().insertInTx(itemsBeans);
                                }
//                    MyApp.getInstance().getDaoSession().getGoodsBeanDao().insertInTx(itemsBeans);

                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }


    }

    private void getcus() {
        Map<String, Object> request = new HashMap<>();
        request.put("table", "CUSTOMER");
        request.put("page", 1);
        request.put("pagesize", 1);
        request.put("dbname", dbname);
        NetHelper.request().downCus(request).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer<RequestCus>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(RequestCus requestCus) {
                if (requestCus == null) {
                    return;
                }
               downCus(Integer.parseInt(requestCus.getCount()));
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }
    public void downCus(int max) {
        Api api = NetHelper.request();
        int pageTotal = max / 400+1; //合计请求次数
        for (int index = 1; index <= pageTotal; index++) {
            Map<String, Object> request = new HashMap<>();
            request.put("table", "CUSTOMER");
            request.put("page", index);
            request.put("pagesize", String.valueOf(400));
            request.put("dbname", dbname);
            api.downCus(request).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer<RequestCus>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(RequestCus requestCus) {
                    if (requestCus == null) {
                        return;
                    }
                    if (requestCus.getFlag() == 1) {

                        List<CusBean> itemsBeans = requestCus.getResult();
                        if (itemsBeans.size() > 0) {
                            MyApp.getInstance().getDaoSession().getCusBeanDao().deleteAll();
                            MyApp.getInstance().getDaoSession().getCusBeanDao().insertInTx(itemsBeans);

                        }
//                    MyApp.getInstance().getDaoSession().getGoodsBeanDao().insertInTx(itemsBeans);

                    }
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
        }


    }
    public void downUser() {
        Map<String, Object> request = new HashMap<>();
        request.put("table", "USER");
        request.put("page", String.valueOf(1));
        request.put("pagesize", String.valueOf(400));
        request.put("dbname", dbname);
        NetHelper.request().downUser(request).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer<RequestUser>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(RequestUser requestUser) {
                if (requestUser == null) {
                    return;
                }
                if (requestUser.getFlag() == 1) {

                    List<UserBean> itemsBeans = requestUser.getResult();
                    if (itemsBeans.size() > 0) {
                        MyApp.getInstance().getDaoSession().getUserBeanDao().deleteAll();
                        MyApp.getInstance().getDaoSession().getUserBeanDao().insertInTx(itemsBeans);
                    }
//                    MyApp.getInstance().getDaoSession().getGoodsBeanDao().insertInTx(itemsBeans);

                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }

    public void downStock() {
        Map<String, String> request = new HashMap<>();
        request.put("table", "GOODSSTOCK");
        request.put("page", String.valueOf(page_stock));
        request.put("pagesize", String.valueOf(400));
        request.put("dbname", dbname);
        NetHelper.doPost("/pda/down_base.php", request, new NetHelper.ResponseResult() {
            @Override
            public void success(String result) {
                RequestStock testBean = new Gson().fromJson(result, RequestStock.class);
                if (testBean == null) {
                    RxToast.normal("json解析错误");
                    return;
                }
                if (testBean.getFlag() == 1) {

                    List<StockBean> itemsBeans = testBean.getResult();
                    if (itemsBeans.size() > 0) {
                        MyApp.getInstance().getDaoSession().getStockBeanDao().deleteAll();
                        MyApp.getInstance().getDaoSession().getStockBeanDao().insertInTx(itemsBeans);
                        RxLogTool.d(itemsBeans.size() + "------库存>" + page_stock + "页");
                        page_stock++;
                        downStock();
                    } else {
                        RxToast.normal("库存下载完成");
                    }
//                    MyApp.getInstance().getDaoSession().getGoodsBeanDao().insertInTx(itemsBeans);

                }
            }

            @Override
            public void failed(String msg) {

            }
        });
    }

    private void getbrand() {
        Map<String, Object> request = new HashMap<>();
        request.put("table", "GOODSBRAND");
        request.put("page",1);
        request.put("pagesize", 1);
        request.put("dbname", dbname);
        NetHelper.request().downBrand(request).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer<RequestBrand>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(RequestBrand requestBrand) {
                if (requestBrand == null) {
                    return;
                }
               downBrand(Integer.parseInt(requestBrand.getCount()));
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }
    public void downBrand(int max) {
        Api api = NetHelper.request();
        int pageTotal = max / 400+1; //合计请求次数
        for (int index = 1; index <= pageTotal; index++) {
            Map<String, Object> request = new HashMap<>();
            request.put("table", "GOODSBRAND");
            request.put("page",index);
            request.put("pagesize", String.valueOf(400));
            request.put("dbname", dbname);
            api.downBrand(request).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer<RequestBrand>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(RequestBrand requestBrand) {
                    if (requestBrand == null) {
                        return;
                    }
                    if (requestBrand.getFlag() == 1) {

                        List<BrandBean> itemsBeans = requestBrand.getResult();
                        if (itemsBeans.size() > 0) {
                            MyApp.getInstance().getDaoSession().getBrandBeanDao().deleteAll();
                            MyApp.getInstance().getDaoSession().getBrandBeanDao().insertInTx(itemsBeans);

                        }
//                    MyApp.getInstance().getDaoSession().getGoodsBeanDao().insertInTx(itemsBeans);

                    }
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
        }

    }


    private void getCat() {
        Map<String, Object> request = new HashMap<>();
        request.put("table", "GOODSCAT");
        request.put("page", 1);
        request.put("pagesize", 1);
        request.put("dbname", dbname);
        NetHelper.request().downCat(request).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer<RequestCat>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(RequestCat requestCat) {
                if (requestCat == null) {
                    return;
                }
              downCat(Integer.parseInt(requestCat.getCount()));
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }
    public void downCat(int max) {
        Api api = NetHelper.request();
        int pageTotal = max / 400+1; //合计请求次数
        for (int index = 1; index <= pageTotal; index++) {
            Map<String, Object> request = new HashMap<>();
            request.put("table", "GOODSCAT");
            request.put("page", index);
            request.put("pagesize", String.valueOf(400));
            request.put("dbname", dbname);
            api.downCat(request).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer<RequestCat>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(RequestCat requestCat) {
                    if (requestCat == null) {
                        return;
                    }
                    if (requestCat.getFlag() == 1) {

                        List<CatBean> itemsBeans = requestCat.getResult();
                        if (itemsBeans.size() > 0) {
                            MyApp.getInstance().getDaoSession().getCatBeanDao().deleteAll();
                            MyApp.getInstance().getDaoSession().getCatBeanDao().insertInTx(itemsBeans);
                        }
//                    MyApp.getInstance().getDaoSession().getGoodsBeanDao().insertInTx(itemsBeans);

                    }
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
        }

    }
    int pro = 0;
    private void showDilog(int max){

        dialog = new ProgressDialog(mContext);
        dialog.setProgress(0);
        dialog.setCancelable(false);
        dialog.show();


    }

    private void upPro(final ProgressDialog dialog, final int max) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (pro <max) {
                    upProgress(pro);
                    pro+=400;
                    try {
                        Thread.sleep(1400);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
                pro = 0;


            }
        }).start();
    }


    private void upProgress(int pro) {
        dialog.setProgress(pro);
    }

}
